package com.heima.behavior.service.impl;

import com.heima.behavior.service.UnLikesBehaviorService;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.BehaviorRedisKeyEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UnLikesBehaviorServiceImpl implements UnLikesBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 不喜欢或取消不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        // 1.检查参数
        if (dto.getArticleId() == null || dto.getType() == null) {
            return ResponseResult.error(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2.获取当前用户
        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null) {
            return ResponseResult.error(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 3.根据操作类型执行不喜欢或取消不喜欢
        String unLikeKey = BehaviorRedisKeyEnum.UNLIKES_BEHAVIOR_PREFIX.buildKey(dto.getArticleId());

        if (dto.getType() == 0) {
            // 不喜欢操作，添加到Redis set中
            stringRedisTemplate.opsForSet().add(unLikeKey, String.valueOf(user.getId()));
        } else {
            // 取消不喜欢操作，从Redis set中移除
            stringRedisTemplate.opsForSet().remove(unLikeKey, String.valueOf(user.getId()));
        }

        return ResponseResult.success(AppHttpCodeEnum.SUCCESS);
    }
}
